import { UuidBasic } from '../textTOvoice/UuidBasic';
import { CarControlService } from './CarControlService';
import { EnhancedKnowledgeBase } from '../data/EnhancedKnowledgeBase';
import { TtsManager } from '../textTOvoice/TtsManager';

// 兼容性定义
declare namespace textToSpeech {
  interface SpeakListener {
    onStart: () => void;
    onComplete: () => void;
    onError: (id: string, code: number, msg: string) => void;
  }
}

export class VoiceService {
  private carControlService: CarControlService = CarControlService.getInstance();
  private knowledgeBase: EnhancedKnowledgeBase = new EnhancedKnowledgeBase();
  private ttsManager: TtsManager;
  private onResponse: (text: string) => void;
  public isSpeaking: boolean = false;

  constructor(onResponse: (text: string) => void) {
    this.onResponse = onResponse;
    this.initializeTts();
  }

  private initializeTts(): void {
    const ttsListener: any = { // 使用 any 避免编译错误
      onStart: () => {
        console.info("VoiceService: TTS started.");
        this.isSpeaking = true;
      },
      onComplete: () => {
        console.info("VoiceService: TTS completed.");
        this.isSpeaking = false;
      },
      onError: (id, code, msg) => {
        console.error(`VoiceService: TTS Error: ${msg}`);
        this.isSpeaking = false;
        this.onResponse(`语音合成错误: ${msg}`);
      }
    };
    this.ttsManager = new TtsManager(ttsListener);
    this.ttsManager.init().catch(error => {
      console.error("Failed to initialize TTS Manager", error);
      this.onResponse("TTS引擎初始化失败");
    });
  }

  public processText(text: string): void {
    console.info(`VoiceService: Processing received text: "${text}"`);
    const result = this.knowledgeBase.findBestResponse(text);
    const response = typeof result === 'string' ? result : (result.action ? this.carControlService.executeAction(result.action, result.parameters) : result.response);

    console.info(`VoiceService: Generated response: "${response}"`);
    this.onResponse(response); // 将响应回调给UI层
    this.ttsManager.speak(response);
  }

  public stopSpeaking(): void {
    if (this.ttsManager) {
      this.ttsManager.stop();
    }
  }

  public cleanup(): void {
    if (this.ttsManager) {
      this.ttsManager.shutdown();
    }
  }
} 